package Tracker.http;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import org.apache.commons.io.IOUtils;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

public class Uploader implements HttpHandler {
	public void handle(HttpExchange t) throws IOException {

		Socket socket = new Socket("127.0.0.1", 9001);

		t.getResponseHeaders().add("Content-Type", "application/json");
		t.sendResponseHeaders(200, 0);
//
//		// Request (From Browser)
//		PrintWriter sockOut = new PrintWriter(socket.getOutputStream(), true);
//		BufferedReader httpIn = new BufferedReader(new InputStreamReader(
//				t.getRequestBody()));

		// Response (To Browser)
		PrintWriter httpOut = new PrintWriter(t.getResponseBody());
		InputStreamReader sockIn = new InputStreamReader(
				socket.getInputStream());
		char[] resChar = new char[1024];
		String response = null;

//		JSONObject command = new JSONObject(httpIn.readLine());
//		System.out.println("Client --> " + command);
//
//		if (!command.isNull("command")) {
//			String session = cmdMatch.group(1);
//			String name = cmdMatch.group(2);
//
//			sockOut.println("{ \"command\" : \"upload\", \"session\" : "
//					+ session + ", \"name\" : \"" + name + "\" }");
			IOUtils.copy(t.getRequestBody(), socket.getOutputStream());

			sockIn.read(resChar);
			response = new String(resChar);
//		} else {
//			response = "{ \"success\" : false, \"error\" : { \"message\" : " +
//					"\"Invalid upload request\", \"code\" : 400 } }";
//		}

		System.out
				.println("Server --> (" + response.length() + ") " + response);
		httpOut.println(response.trim());

		httpOut.close();
		System.out.println("HTTP Response Closed");
		socket.close();
		System.out.println("TCP Socket Closed");

	}
}
